//
//  WBWelcomeView.swift
//  Weibo
//
//  Created by niqiang on 16/7/11.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import UIKit
import SDWebImage

class WBWelcomeView: UIView {
    
    @IBOutlet weak var iconView: UIImageView!
    
    @IBOutlet weak var tipLabel: UILabel!
    
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    
    //图标宽度约束  ———— 用户设置图标（用户头像）圆角
    @IBOutlet weak var iconWidthCons: NSLayoutConstraint!
    
    class func welcomeView() -> WBWelcomeView {
        let nib = UINib(nibName: "WBWelcomeView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView
        
        v.frame = UIScreen.main().bounds
        
        return v
        
    }
    
    override func awakeFromNib() {
        //1url
        guard let urlString = WBNetworkManager.shared.userAccount.avatar_large,
            let url = URL(string: urlString) else{
        return
        }
        
        //2.设置头像   如果网络没有加载完成，先设置占位头像
        iconView.sd_setImage(with: url,placeholderImage: UIImage(named: "avatar_default_big"))
        
        // - 3.设置圆角 （用XIB时 iconView的bounds 还没有设置）
        iconView.layer.cornerRadius = iconWidthCons.constant * 0.5
        iconView.layer.masksToBounds = true
    }
    
    //视图被添加到window上，表示视图已经显示
    override func didMoveToWindow() {
        super.didMoveToWindow()
        
        // 视图是使用自动布局来设置的，只是设置了约束
        // - 当视图被添加到窗口上时，根据父视图的大小，计算约束值，更新控件位置
        // - layoutIfNeeded 会直接按照当前的约束直接更新控件位置
        // - 执行之后，控件所在位置，就是 XIB 中布局的位置

        self.layoutIfNeeded()
        
        bottomCons.constant = bounds.size.height - 200
    
        //如果控件们的frame 还没设置好！，所有的约束会一起动画
        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
        //更新约束
        self.layoutIfNeeded()
        }) { (_) in
            
            UIView.animate(withDuration: 1.0, animations: {self.tipLabel.alpha = 1}, completion: { (_) in
                self.removeFromSuperview()
            })
        }
    }
}
